<template>
   <div class="app-container">
      <div class="head-container">
         <a-form :model="queryParams" ref="queryRef" layout="inline">
            <a-form-item prop="jobName">
               <a-input v-model="queryParams.jobName" placeholder="请输入任务名称" clearable style="width: 200px" />
            </a-form-item>
            <a-form-item prop="jobGroup">
               <a-select v-model="queryParams.jobGroup" placeholder="请选择任务组名" clearable style="width: 200px">
                  <a-option v-for="dict in sys_job_group" :key="dict.value" :label="dict.label" :value="dict.value" />
               </a-select>
            </a-form-item>
            <a-form-item prop="status">
               <a-select v-model="queryParams.status" placeholder="请选择任务状态" clearable style="width: 200px">
                  <a-option v-for="dict in sys_job_status" :key="dict.value" :label="dict.label" :value="dict.value" />
               </a-select>
            </a-form-item>
            <a-form-item>
               <a-space>
                  <a-button type="primary" @click="handleQuery">
                     <template #icon>
                        <icon-search />
                     </template>
                     搜索</a-button>
                  <a-button @click="resetQuery">
                     <template #icon>
                        <icon-refresh />
                     </template>
                     重置</a-button>
               </a-space>
            </a-form-item>
         </a-form>
      </div>
      <div class="main-container">
         <div class="main-toolbar">
            <a-button type="primary" @click="handleAdd">
               <template #icon>
                  <icon-plus />
               </template>
               新增</a-button>
            <a-button status="success" :disabled="selectedKeys.length !== 1" @click="handleUpdate">
               <template #icon>
                  <icon-edit />
               </template>
               修改</a-button>
            <a-button status="danger" :disabled="selectedKeys.length === 0" @click="handleDelete">
               <template #icon>
                  <icon-delete />
               </template>
               删除</a-button>
            <a-button status="info" @click="handleJobLog">
               <template #icon>
                  <icon-info-circle />
               </template>
               日志</a-button>
         </div>
         <div class="main-content">
            <a-table :columns="cloumns" :data="jobList" row-key="id"
               :row-selection="{ type: 'checkbox', showCheckedAll: true }" @selection-change="handleSelectionChange">
               <template #status="{ record }">
                  <a-switch v-model="record.status" @change="handleStatusChange(record)" type="round" checked-value="0"
                     unchecked-value="1">
                     <template #checked>
                        启用
                     </template>
                     <template #unchecked>
                        停用
                     </template>
                  </a-switch>
               </template>
            </a-table>
         </div>
      </div>
   </div>
</template>

<script setup name="Job">
import { addJob, changeJobStatus, delJob, getJob, listJob, runJob, updateJob } from "@/api/monitor/job";
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_job_group, sys_job_status } = proxy.useDict("sys_job_group", "sys_job_status");

const jobList = ref([]);
const open = ref(false);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const openView = ref(false);
const openCron = ref(false);
const expression = ref("");

const data = reactive({
   form: {},
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      jobName: undefined,
      jobGroup: undefined,
      status: undefined
   },
   rules: {
      jobName: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
      invokeTarget: [{ required: true, message: "调用目标字符串不能为空", trigger: "blur" }],
      cronExpression: [{ required: true, message: "cron执行表达式不能为空", trigger: "change" }]
   }
});

const { queryParams, form, rules } = toRefs(data);

const cloumns = ref([
   { key: 0, title: '编号', dataIndex: 'id' },
   { key: 1, title: 'beanName', dataIndex: 'beanName' },
   { key: 2, title: '参数', dataIndex: 'params' },
   { key: 3, title: 'cron执行表达式', dataIndex: 'cronExpression' },
   { key: 4, title: '状态', dataIndex: 'status', slotName: 'status' },
   { key: 5, title: '备注', dataIndex: 'remark' },
   { key: 6, title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } }
])

const selectedKeys = ref([]);
/** 查询定时任务列表 */
function getList() {
   loading.value = true;
   listJob(queryParams.value).then(({ data }) => {
      jobList.value = data.rows;
      total.value = data.total;
      loading.value = false;
   });
}
/** 任务组名字典翻译 */
function jobGroupFormat(row, column) {
   return proxy.selectDictLabel(sys_job_group.value, row.jobGroup);
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {
   form.value = {
      jobId: undefined,
      jobName: undefined,
      jobGroup: undefined,
      invokeTarget: undefined,
      cronExpression: undefined,
      misfirePolicy: 1,
      concurrent: 1,
      status: "0"
   };
   proxy.resetForm("jobRef");
}
/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
   selectedKeys.value = selection
}
// 更多操作触发
function handleCommand(command, row) {
   switch (command) {
      case "handleRun":
         handleRun(row);
         break;
      case "handleView":
         handleView(row);
         break;
      case "handleJobLog":
         handleJobLog(row);
         break;
      default:
         break;
   }
}
// 任务状态修改
function handleStatusChange(row) {
   let text = row.status === "0" ? "启用" : "停用";
   proxy.$modal.confirm({
      title: '系统提示',
      content: `确认要${text}${row.beanName}任务吗?`,
      onOk: function () {
         changeJobStatus(row.jobId, row.status).then(() => {
            proxy.$message.success(text + "成功");
         }).catch(() => {
            row.status = row.status === "0" ? "1" : "0";
         })
      },
      onCancel: () => {
         row.status = row.status === "0" ? "1" : "0";
      }
   })
}
/* 立即执行一次 */
function handleRun(row) {
   proxy.$modal.confirm('确认要立即执行一次"' + row.jobName + '"任务吗?').then(function () {
      return runJob(row.jobId, row.jobGroup);
   }).then(() => {
      proxy.$modal.msgSuccess("执行成功");
   })
      .catch(() => { });
}
/** 任务详细信息 */
function handleView(row) {
   getJob(row.jobId).then(response => {
      form.value = response.data;
      openView.value = true;
   });
}
/** cron表达式按钮操作 */
function handleShowCron() {
   expression.value = form.value.cronExpression;
   openCron.value = true;
}
/** 确定后回传值 */
function crontabFill(value) {
   form.value.cronExpression = value;
}
/** 任务日志列表查询 */
function handleJobLog(row) {
   const jobId = row.jobId || 0;
   router.push('/monitor/job-log/index/' + jobId)
}
/** 新增按钮操作 */
function handleAdd() {
   reset();
   open.value = true;
   title.value = "添加任务";
}
/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   const jobId = row.jobId || ids.value;
   getJob(jobId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改任务";
   });
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["jobRef"].validate(valid => {
      if (valid) {
         if (form.value.jobId != undefined) {
            updateJob(form.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               getList();
            });
         } else {
            addJob(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}
/** 删除按钮操作 */
function handleDelete(row) {
   const jobIds = row.jobId || ids.value;
   proxy.$modal.confirm('是否确认删除定时任务编号为"' + jobIds + '"的数据项?').then(function () {
      return delJob(jobIds);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}
/** 导出按钮操作 */
function handleExport() {
   proxy.download("monitor/job/export", {
      ...queryParams.value,
   }, `job_${new Date().getTime()}.xlsx`);
}

getList();
</script>
